//
//  GRSearchTextField.m
//  YC_GRice
//
//  Created by LiuFeng on 2018/7/14.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRSearchTextField.h"

@interface GRSearchTextField () <UITextFieldDelegate>

@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIImageView *glassIMG;

@end

@implementation GRSearchTextField

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self drawUI:frame];
    }
    return self;
}


-(void)drawUI:(CGRect)frame {
    self.backgroundColor     = KGMBACKGROUND_COLOR;
    self.layer.cornerRadius  = 3;
    self.layer.masksToBounds = YES;
    
    _glassIMG = [[UIImageView alloc] initWithFrame:CGRectMake(5, frame.size.height/2-7.5, 15, 15)];
    _glassIMG.image = [UIImage imageNamed:@"glass"];
    [self addSubview:_glassIMG];
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(25, 0, frame.size.width-35, frame.size.height)];
    _textField.delegate = self;
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textField.textAlignment   = NSTextAlignmentLeft;
    _textField.placeholder     = @"搜索";
    _textField.font            = [UIFont systemFontOfSize:14];
    _textField.returnKeyType   = UIReturnKeySearch;
    [_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self addSubview:_textField];
}



-(void)setText:(NSString *)text {
    self.textField.text = text;
}

-(void)setPlaceholder:(NSString *)placeholder {
    self.textField.placeholder = placeholder;
}

-(NSString *)text {
    return self.textField.text;
}

- (BOOL)resignFirstResponder {
    [super resignFirstResponder];
    return [self.textField resignFirstResponder];
}

-(BOOL)isFirstResponder {
    [super isFirstResponder];
    return self.textField.isFirstResponder;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([self.delegate respondsToSelector:@selector(didClickedSearchButton:)]) {
        [self.delegate didClickedSearchButton:textField];
    }
    return YES;
}


-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([self.delegate respondsToSelector:@selector(searchTextFieldShouldBeginEditing:)]) {
        return [self.delegate searchTextFieldShouldBeginEditing:textField];
    }
    return YES;
}

- (void)textFieldDidChange:(UITextField *)textField {
    if ([self.delegate respondsToSelector:@selector(searchTextDidChange:)]) {
        [self.delegate searchTextDidChange:textField];
    }
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
